package com.ziyucoding.springboot.labs.lab10.seatdemo.tccscfeign.transactionrecordservice.controller;

import com.ziyucoding.springboot.labs.lab10.seatdemo.tccscfeign.transactionrecordservice.dataobject.TransactionalRecordDO;
import com.ziyucoding.springboot.labs.lab10.seatdemo.tccscfeign.transactionrecordservice.dto.TransactionalRecordSaveDTO;
import com.ziyucoding.springboot.labs.lab10.seatdemo.tccscfeign.transactionrecordservice.service.TransactionalRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 事务记录 控制器
 *
 * @author ziyucoding
 * @date 2022-11-06
 **/
@RestController
@RequestMapping("/transactional-record")
public class TransactionalRecordController {

    private Logger logger = LoggerFactory.getLogger(TransactionalRecordController.class);

    @Autowired
    private TransactionalRecordService transactionalRecordService;

    @PostMapping("/save")
    public Map<String, Object> saveTransactionalRecord(@RequestBody TransactionalRecordSaveDTO dto) {
        logger.info("[saveTransactionalRecord] 收到保存事务记录请求, xid:{}, status:{}", dto.getXid(),
                dto.getStatus());
        boolean isSuccess = false;
        try {
            TransactionalRecordDO item = new TransactionalRecordDO();
            item.setXid(dto.getXid());
            item.setStatus(dto.getStatus());
            transactionalRecordService.saveTransactionalRecord(item);
            isSuccess = true;
        } catch (Exception e) {
            logger.error("保存事务记录失败", e);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "成功");
        result.put("data", isSuccess);
        return result;
    }

    @GetMapping("/find-by-id")
    public Map<String, Object> findTransactionalRecordByXid(@RequestParam("xid") String xid) {
        boolean isSuccess = true;
        TransactionalRecordDO item = null;
        try {
            item = transactionalRecordService.findByXid(xid);
        } catch (Exception e) {
            logger.error("获取事务记录失败", e);
            isSuccess = false;
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "成功");

        Map<String, Object> data = new HashMap<>();
        data.put("isSuccess", isSuccess);
        data.put("item", item);
        result.put("data", data);
        return result;
    }
}
